<template>
	<view>
		<view class="u-page">
			<view class="commonPopup alcenter">
				<view class="bg forbid" v-if="forbid">
					<image class="danger" :src="API_PREFIX + '/mobile/wxImages/daka/3.png'" mode="aspectFill"></image>
					<div class="tip">提示：{{globalConfig.forbidText || '当前你不宜进入公共场所，请尽快前往医院进行检测！'}}</div>
				</view>
				<view class="bg" v-else>
					<image class="success" v-if="dkSuccess==1" :src="API_PREFIX + '/mobile/wxImages/daka/1.png'" mode="aspectFill"></image>
					<image class="fail" v-if="dkSuccess==2" :src="API_PREFIX + '/mobile/wxImages/daka/2.png'" mode="aspectFill"></image>
					<div class="tip" v-if="errorMsg">提示：{{errorMsg}}</div>
				</view>

				<view v-if="dkInfo" class="titlehz">个人惠泽码</view>
				<uqrcode v-if="dkInfo" ref="uQRCode" backgroundColor="#efeff4" :text="grhzmString" size="150"/>

                <view class="cyInfo" v-if="dkInfo && hasHs" :class="'_' + hasHs">
                    <text>{{hasHs == 1 ? '今日已采样' : '今日未采样'}}</text>
                </view>
				<view v-if="dkInfo" class="dkInfo">
					<view class="leninfo"><view class="key">打卡场所 </view> <view class="value">{{dkInfo.shmc}}</view></view>
					<!-- <view class="leninfo"><view class="key">当前位置</view> <view class="value">{{dkInfo.addr | addrFmt}}</view></view> -->
					<view class="leninfo"><view class="key">打卡时间</view><view class="value">{{dkInfo.createTime}}</view></view>

					<view class="leninfo"><view class="key">苏康码</view><view class="value" :style="skmStyle"><u-loading-icon v-if="!skmInfo"></u-loading-icon> <text v-else>{{skmInfo}}</text> </view></view>
					<view class="leninfo"><view class="key">核酸检测结果</view><view class="value" :style="hsStyle"><u-loading-icon v-if="!hsInfo"></u-loading-icon><text v-else>{{hsInfo}}</text> </view></view>
				</view>
				<view class="extInfo" v-if="!dkSuccess && isKaKou">
				<!-- <view class="extInfo"> -->
					<view class="text">补充信息</view>
					
                    <!--                    <view class="leninfo" v-show="kakouType == 'hotel'">
						<view class="key">来源地</view>
						<view class="value">
							<regionPicker ref="regionPicker" :multiIndex_="provinceCityArea" 
							@selecteRegion_="selecteProvinceCityArea($event, item)" :column_="3"></regionPicker>
						</view>
					</view> -->

					<!-- <view class="leninfo" v-show="kakouType == 'kakou'">
						<view class="key">目的地</view>
						<view class="value" @click="openMddPicker()">
							<u--input v-model="mdd" placeholder="请选择目的地" border="none" disabled></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</view>
						<my-u-picker immediateChange :show="showMddPicker" keyName="name" 
							:columns="mddColumns" @confirm="openMddPickerConfirm"
							@cancel="onMddPickerClose()" @close="onMddPickerClose()" closeOnClickOverlay></my-u-picker>
					</view>

					<view class="extBtn">
                        <u-button text="确定打卡/提交" type="primary" @click="submitDk()"></u-button>
					</view> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import getLocation from '@/utils/getLocation.js'
	import { mapState, mapMutations } from 'vuex';
	import sceneMixins from '@/utils/sceneMixins';
	import regionPicker from '@/components/region-picker/region-picker.vue';
	import Base64 from 'base-64';
	export default {
		components: {regionPicker},
		mixins: [getLocation, sceneMixins],
		data() {
			return {
                API_PREFIX: this.API_PREFIX,
				label: '',
				showPopup: false,
				commonPopupInfo: ''	,
				dkInfo: '',
				errorMsg: '',
				dkSuccess: 0,
                forbid: false,
				skmStyle: '',
				hsStyle: '',
				hsInfo: '',
				skmInfo: '',
                
				hasHs: 0,
                
				isKaKou: false,
				provinceCityArea: [],
				provinceName: '',

				mdd: '',
				showMddPicker: false,
				mddColumns: [[{"id":"320724900","name":"化工园区"},{"id":"320724901","name":"经济开发区"},{"id":"320724902","name":"临港产业园区"},{"id":"320724903","name":"农业园区"},{"id":"320724100","name":"新安镇"},{"id":"320724101","name":"堆沟港镇"},{"id":"320724103","name":"北陈集镇"},{"id":"320724104","name":"张店镇"},{"id":"320724105","name":"汤沟镇"},{"id":"320724106","name":"百禄镇"},{"id":"320724107","name":"孟兴庄镇"},{"id":"320724108","name":"三口镇"},{"id":"320724109","name":"田楼镇"},{"id":"320724110","name":"新集镇"},{"id":"320724203","name":"李集镇"}]],
                kakouType: '',

				grhzmString: ''
            }
		},
		computed: {
			...mapState(['globalConfig', 'userInfo'])
		},
		options: {
			styleIsolation: 'shared'
		},
		filters: {
			addrFmt: function (v) {
				return v.replace(/^江苏省连云港市/, '')
			}
		},
        onShow(options) {
            var vm = this;
            let pages = getCurrentPages();
            let currPage = pages[ pages.length - 1];
            if(currPage.data.callBackData){
				vm.waitDakaInput = false;
                vm.submitDk(currPage.data.callBackData);
                currPage.data.callBackData = undefined;
            } else if (vm.waitDakaInput) {
                uni.showLoading({title: '等待信息补充, 即将自动跳转', mask: true});
                setTimeout(() => {
					var json = '';
					if (vm.kakouType == 'hotel') {
						json = vm.isReport ? '/mobile/wxJSON/daka/reported.json' : '/mobile/wxJSON/daka/noReport.json';
					} else {
						json = `/mobile/wxJSON/daka/${vm.kakouType}.json`;
					}
                    uni.navigateTo({
                        url: '/pages/shanghuma/input?loadJSON=' + json
                    })
                }, 1000)
            }
        },
		onLoad(options) {
			var vm = this;
			if (options.title) {
				uni.setNavigationBarTitle({
					title: options.title
				});
			}
			// debugger
			var value = options.value;
			if (!value) {
				uni.$u.toast('无效的访问地址');
				uni.redirectTo({ url: '/pages/index/index' })
			} else {
				vm.shmId = value;
				vm.doWxLogin().then(res => {
					vm.openId = res.openId;
					uni.showLoading({title: '请稍后'});
					var getLocationTimeout = setTimeout(() => {
						uni.hideLoading();
						vm.doDakaFail('获取定位超时，请检查您的网络环境，位置信息是否打开，或检查微信的位置权限。');
					}, 5000);
					vm.getUserLocation().then(res => {
						clearTimeout(getLocationTimeout);
						uni.hideLoading();
						vm.position = res;
						vm.doDk();
					}).catch(e => {
						vm.doDakaFail('获取定位失败');
					});
					vm.waitVariable('userInfo').then((userInfo) => {
						vm.grhzmString = vm.openId + '+' + Base64.encode(userInfo.credentialsNo);

                        vm.getAndLoad('核酸采样', '/mobile/ymt/owncenter/hscy/getResult.jsp?openId=' + vm.openId, (res) => {
                           vm.hasHs = res.data.hasHs ? 1 : 2;
                        });
						vm.getAndLoad('苏康码', `/mobile/ymt/skmHs/getInfo.jsp?type=skm&userName=${userInfo.userName}&idCard=${userInfo.credentialsNo}`, function (res2) {
							if (res2.code == 0) {
								vm.skmInfo = res2.data.levelDescribed;
								if (vm.skmInfo == '绿码') {
									vm.skmStyle = 'color:green;';
								} else if (vm.skmInfo == '红码') {
									vm.forbid = 2;
									vm.skmStyle = 'color:red;';
								} else if (vm.skmInfo == '黄码') {
									vm.forbid = 2;
									vm.skmStyle = 'color:orange;';
								}
							} else {
								vm.skmInfo = res2.msg;
							}
						});
						vm.getAndLoad('核酸报告', `/mobile/ymt/skmHs/getInfo.jsp?type=hs&userName=${userInfo.userName}&idCard=${userInfo.credentialsNo}`, function (res2) {
							if (res2.code == 1) {
								vm.hsInfo = res2.msg;
							} else if (res2.datas && res2.datas[0]) {
								var result = res2.datas[0];
								var detalTime = new Date().getTime() - new Date(result.hsjcsj.replace(/-/g, '/')).getTime();
								var tipMore = '';
								if (detalTime < 24 * 60 * 60 * 1000) {
									tipMore = '(24小时以内)';
								} else if (detalTime < 48 * 60 * 60 * 1000) {
									tipMore = '(48小时以内)';
								}
								vm.hsInfo = `${result.hsjcjg}${tipMore}\n${result.hsjcsj}`;
								if (result.hsjcjg == '阴性') {
									vm.hsStyle = 'color:green;';
								} else if (result.hsjcjg == '阳性') {
									vm.forbid = 2;
									vm.hsStyle = 'color:red;';
								}
							} else {
								vm.hsInfo = '未查到近期结果';
							}
						});
					});
					
				});
			}
		},
		methods: {
			...mapMutations(['setPosition']),
			doDakaSuccess: function (res) {
				this.dkInfo = res.data;
				this.dkSuccess = 1;
			},
			doDakaFail: function (res) {
				this.label = '打卡失败';
				this.errorMsg = res;
				this.dkSuccess = 2;
			},
			selecteProvinceCityArea(data) {
				var vm = this;
				vm.provinceCityArea = data.code;
				var areaCode = data.code.length ? data.code.slice(-1)[0] : '';
				vm.provinceName = data.name.join('-');
				vm.provinceCode = areaCode;
			},
			checkIsKakou: function () {
				var vm = this;
				return new Promise(resolve => {
					var postUrl = `/mobile/h5/covid19/apiShm/qdLog/checkIsKaKou.jsp?openId=${vm.openId}&shmId=${vm.shmId}`;
					vm.getAndLoad('判断是否是卡口', postUrl, function (res2) {
						resolve(res2.data);
					});
				})

			},
			doDk: function () {
				var vm = this;
				vm.checkIsKakou().then((data) => {
					var isKaKou = data.isKaKou;
					if (!isKaKou) {
						vm.submitDk();
					} else {
						vm.isKaKou = true;
                        vm.kakouType = data.type;
                        vm.isReport = data.isReport;
						uni.$u.toast('需要补充一下信息');
                        setTimeout(() => {
							if (!data.type) {
								uni.showLoading({title: '等待信息补充, 即将自动跳转', mask: true});
							} else {
								if (data.type == 'hotel') {
									vm.waitDakaInput = true;
									var json = data.isReport ? '/mobile/wxJSON/daka/reported.json' : '/mobile/wxJSON/daka/noReport.json';
									uni.navigateTo({
										url: '/pages/shanghuma/input?loadJSON=' + json
									})
								} else {
									vm.waitDakaInput = true;
									uni.navigateTo({
										url: '/pages/shanghuma/input?loadJSON=/mobile/wxJSON/daka/' + data.type + '.json'
									})
								}
							}
                            
                        }, 1000)
					}
				});
			},
			submitDk: function (params) {
				var vm = this;
				if (vm.isKaKou) {
					// if (vm.kakouType == 'kakou' && !vm.mdd) {
					// 	uni.$u.toast('请选择目的地');
					// 	return;
					// }
				}
				var postUrl = '/mobile/h5/covid19/apiShm/qdLog/save.jsp?' 
					+ vm.$Util.stringify({ openId: vm.openId, shmId: vm.shmId, lng: vm.position.longitude, lat: vm.position.latitude, mdd: vm.mdd, mddId: vm.mddId, ...params });
				 uni.showLoading({title: '正在打卡', mask: true});
                vm.getAndLoad('打卡', postUrl, function (res2) {
                    uni.hideLoading();
					if (res2.code == 0) {
						vm.doDakaSuccess(res2);
					} else {
						vm.doDakaFail(res2.msg);
					}
				});
			},
			onMddPickerClose: function () {
				this.showMddPicker = false;
			},
			openMddPicker: function () {
				this.showMddPicker = true;
			},

			openMddPickerConfirm: function (v) {
				console.log(v);
				this.mdd = v.value[0].name;
				this.mddId = v.value[0].id;
				this.showMddPicker = false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-page {
	}
	.bg {
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
		image {
			width: 600rpx;
			height: 391rpx;
            margin-top: 20rpx;
		}
        .tip {
            padding: 0 50rpx;
            font-size: 28rpx;
            text-indent: 2rem;
            color: #544f4f;
            margin-top: -80rpx;
        }
        &.forbid .tip{
            color: red !important;
        }
	}
	.btn {
		margin: 30rpx 30rpx;
		width: 690rpx;
		height: 220rpx;
	}
	.commonPopup {
		/deep/ .u-popup__content {
			background: transparent;
			border-radius: 20rpx;
		}

	}
    .dkInfo {
        background: #fff;
        overflow: hidden;
        font-size: 30rpx;
		margin-top: 20rpx;
		width: 100%;
    }
	.leninfo {
        line-height: 50rpx;
        display: flex;
		margin: 10rpx 30rpx;
		padding: 10rpx 0rpx;
		position: relative;
        &:not(:last-child) {
             border-bottom: 1px solid #e4e4e4;
        }
		.key {
			min-width: 220rpx;
            color: #909090;
			white-space: nowrap;
		}
		.value {
            text-align: right;
            flex-grow: 1;
			/deep/ .u-loading-icon {
				display: inline-block;
			}
		}
		/deep/ {
			.u-input {
				background: #fff !important;
			}
			.u-popup__content  {
				background: #fff;
			}
			.u-icon--right {
				position: absolute;
				right: 20px;
				top: 10px;
			}
		}
	}
	.extInfo {
  background: #fff;
  margin-top: 20px;
  overflow: hidden;
  .text {
    margin: 20rpx 10rpx;
  }
  .extBtn {
    margin: 40rpx 40rpx;
    width: calc(100% - 80rpx);
  }
}

.cyInfo {
    &._1 {
        color: #59A486;
        border: 2px solid #59A486;
        text {
            border: 1px solid #59A486;
        }
    }
    &._2 {
        color: #E7AF76;
        border: 2px solid #E7AF76;
        text {
            border: 1px solid #E7AF76;
        }
    }

    border-radius: 5px;
    padding: 2px;
    text-align: center;
    font-size: 22px;
    width: 350rpx;
    margin: 30rpx auto 30rpx;
    font-weight: bold;
	zoom: 0.8;
    
    text {
        padding: 10rpx 0rpx;
        width: 100%;
        display: block;
        box-sizing: border-box;
        border-radius: 3px;
    }

}
.titlehz {
	text-align: center;
    margin: -80rpx auto 20rpx;
}
.alcenter {
	display: flex;
    flex-direction: column;
    align-items: center;
}
</style>